import Vue from 'vue'
import Vuex from 'vuex'
import router from '../router'
import createPersistedState from "vuex-persistedstate"
import {
	getUserInfo
} from '@/api/index'
import {
	getQueryString
} from '@/utils/index'
import windowsSDK from '@/common/windows-sdk'
import dayjs from "dayjs";

Vue.use(Vuex)
// 加载模块库-------------------开始
const modulesFiles = require.context('./modules', true, /\.js$/)
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
	const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
	const value = modulesFiles(modulePath)
	modules[moduleName] = value.default
	return modules
}, {});
// 加载模块库-------------------结束

export default new Vuex.Store({
	//持久化store数据
	plugins: [createPersistedState({
		reducer(val) {
			return {
				// userInfo: val.userInfo,
				// deviceInfo: val.deviceInfo,
				// system: val.system,
			}
		}
	})],
	state: {
		system: {
			isTest: false, //测试模式
			indexModule: '1', //首页主题 1：门诊，2：住院
			sdkModule: 'alipayLOT', //SDK模型
			viewModule: process.env.VUE_APP_VIEW_MODULE, //视图模块
			printPaper: 'A5', //打印纸张类型
			canInfraredSensing: false, //红外线传感器（人体感应）
			deviceOpenTime: "06:30", //设备开机时间
			deviceCloseTime: "18:30", //设备关机时间
			isElderMode:false,//长辈模式
			canShutdown:true,//自动开关机
			canCash:false,//是否支持现金充值业务
			canFace:true,//是否支持刷脸
			medicalInsuranceCardReaderType:'1',//1:半插式，2:吸入式
		}, //系统配置信息
		userInfo: {
			name: '', //姓名
			idCard: '', //身份证
			patientId: '', //病人id
			patientCard: '', //就诊卡号
			remainMoney: '', //余额
			tel: '', //手机号码
			isLogin: false, //是否已登录
		},
		hospitalInfo: {
			name: '旭辉健康演示医院',
			id: 'xuhui',
			//机器维修人员
			maintenancePeopleList: [
				{
					tel: '13819734127',
				}
			]
		},
		deviceInfo: {
			sn: '', //设备sn号
			machineNumber: '', //机器号
			adminId: '', //管理员id
			adminName: '', //管理员名字
			ipAddr: '', //自助机局域网ip
			model: '32C', //设备型号
			reportPrintName: 'DASCOM DK-320Z', //报告打印机名字
		},
		loginTimeout: 60, //登录状态超时时间，单位：秒
		loginStatusTimer: null, // 登录状态定时器
		windowsSdkSocketState: '', //windows-sdk的socket连接状态
		showMaintenance: false, //维护页面
		businessList: [{
				label: '当日挂号',
				value: '0101012',
				medicalInsuranceQrcodeValue: '01101',
				url: '/register/type',
			}, {
				label: '预约挂号',
				value: '0101011',
				medicalInsuranceQrcodeValue: '01202',
				url: '/reservation/type',
			},
			{
				label: '打印',
				value: '0101023',
				medicalInsuranceQrcodeValue: '01303',
				url: '/report-print/report',
			}, {
				label: '查询',
				value: '0101022',
				url: '/user-center/index',
			},
			{
				label: '充值',
				medicalInsuranceQrcodeValue: '01104',
				url: '/pay/index',
			},
			{
				label: '缴费',
				medicalInsuranceQrcodeValue: '01301',
				url: '/outpatient-payment/index',
			},
		],
		//头部样式
		headerStyle: {
			fontColor: '#fff'
		},
		visitStepsActive:'register',//就诊流程步骤值，旭辉演示用的
		middlewareOption:{
			state:'fail',
			data:{}
		},//中间件socket的配置
		desKey:'Xuhui@!#',
		expirationTimeState:false,
		recordList:[],
	},
	getters: {
		//是否是安卓设备
		isAndroid(state) {    
			return state.deviceInfo.model == 'B21-D' || state.deviceInfo.model == 'P05A'|| state.deviceInfo.model == 'XYT-01A';
		},
		isWenzhouUrl(state) {
			// return 'http://wjwcfhy.sh.xuhuihealth.com'
			// return state.deviceInfo.addressName=='温州市';
			console.log(state.deviceInfo,'state.deviceInfo')
			switch (state.deviceInfo.addressName) {
				case '温州市':
					// return myConfig.defaultURL
					return 'http://wjwcfhy.sh.xuhuihealth.com'
				default:
					return myConfig.defaultURL
			}
		},
		isWenzhouAddress(state) {
			return state.deviceInfo.addressName=='温州市';
		},

	},
	mutations: {
		setRecordList(state, payload) {
			state.recordList.push(payload)
			if (state.recordList.length > 10) {
				state.recordList.shift(); // 如果数组长度超过10，删除第一条数据
			}

			/*state.recordList.push(payload)
			const endTime = dayjs()
			for (let i = 0; i < state.recordList.length; i++) {
				const startTime = dayjs(state.recordList[i].certificationTime);
				const duration = endTime.diff(startTime, 'day');
				// 判断时间差是否超过3天
				if (duration > 3) {
					console.log('时间超过了3天。');
					state.recordList.splice(i, 1);
				} else {
					console.log('时间没有超过3天。');
				}
			}*/


		},
		setExpirationTimeState(state, payload) {
			state.expirationTimeState = payload
		},
		setMiddlewareState(state, payload) {
			state.middlewareOption.state = payload
		},
		setMiddlewareData(state, payload) {
			state.middlewareOption.data = payload
		},
		setVisitStepsActive(state, payload) {
			state.visitStepsActive = payload
		},
		setHeaderStyle(state, payload) {
			state.headerStyle = {
				...state.headerStyle,
				...payload,
			}
		},
		setLoginTime(state, payload) {
			state.loginTimeout = payload
		},
		setShowMaintenance(state, payload) {
			state.showMaintenance = payload
		},
		setWindowsSdkSocketState(state, payload) {
			state.windowsSdkSocketState = payload
		},
		setSystem(state, payload) {
			state.system = {
				...state.system,
				...payload,
			}
		},
		// 设置用户信息
		setUserInfo(state, userInfo) {
			state.userInfo = {
				...state.userInfo,
				...userInfo,
			}
		},
		//清除用户信息
		clearUserInfo(state, userInfo) {
			state.userInfo = {};
		},
		//清除程序所有信息,并退出登录（不清空用户信息）
		clearAllData(state, userInfo) {
			state.userInfo.isLogin=false;
			state.system.isElderMode=false;
			state['create-record'].info = {};
			state['login'].userInfo = {};
			state['medical-insurance'].info = {};
			state['outpatient-payment'].info = {};
			state['outpatient-payment'].medicalInsuranceInfo = {};
			state['outpatient-payment'].waitPayList = [];
			state['pay'].info = {};
			state['pay'].orderInfo = {};
			state['recharge'].info = {};
			state['register'].info = {};
			state['report-print'].info = {};
			state['reservation'].info = {};
			state['take-number'].info = {};
		},
		setDeviceInfo(state, payload) {
			state.deviceInfo = {
				...state.deviceInfo,
				...payload,
			}
		},
		setHospitalInfo(state, payload) {
			state.hospitalInfo = {
				...state.hospitalInfo,
				...payload,
			}
		},

	},
	actions: {
		
		//退出登录
		logout({
			state,
			commit
		}) {
			commit('setUserInfo', {
				isLogin: false,
			})
			if (state.loginStatusTimer) clearInterval(state.loginStatusTimer);

			if (router.currentRoute.path !== '/index') {
				router.replace({
					path: '/index'
				})
			} else {
				if (state.system.indexModule == '2') {
					// XhAggregation.backHome();
				} else {
					router.replace({
						path: '/index'
					})
				}

			}
		},
		// 刷新登录状态保持时间
		freshLoginStatusTimer({
			state,
			commit,
			dispatch,
		}) {
			// console.log('已登录，开始倒计时')
			if (router.currentRoute.path == '/index') {
				//如果是首页，那就变成30秒倒计时
				if (state.loginStatusTimer) clearInterval(state.loginStatusTimer);
				return
			}else {
				commit('setLoginTime', 60)
			}
			if (state.loginStatusTimer) clearInterval(state.loginStatusTimer);
			state.loginStatusTimer = setInterval(() => {
				// console.log(state.loginTimeout)
				if (state.loginTimeout > 0) {
					commit('setLoginTime', state.loginTimeout - 1);
				} else {
					console.log('倒计时结束，退出登录')
					//时间到，退出登录
					// if (state.userInfo.isLogin) {
					dispatch('logout');
					// }
				}
			}, 1000)
		}
	},
	modules: modules
})